// storage封装
// 在user键下添加abc:{a:1}键值对
// storage.setItem('abc', {a:1}, 'user')
// 删除a下的user键值对
// storage.clear('a', 'user')
const STORAGE_KEY = 'mall'
export default {
  setItem (key, value, moduleName) {
    if (moduleName) {
      let val = this.getItem(moduleName);
      val[key] = value;
      this.setItem(moduleName, val);
    } else {
      let val = this.getStorage();
      val[key] = value;
      window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val))
    }
  },
  // 获取user（key）下面的username（moduleName）
  getItem (key, moduleName) {
    if (moduleName) {
      let val = this.getItem(moduleName);
      if (val) {
        return val[key];
      }
    }
    return this.getStorage()[key];
  },
  getStorage () {
    return JSON.parse(window.sessionStorage.getItem(STORAGE_KEY) || '{}');
  },
  clear (key, moduleName) {
    let val = this.getStorage();
    if (moduleName) {
      if(!val[moduleName]) return;
      delete val[moduleName][key];
    } else {
      delete val[key];
    }
    window.sessionStorage.setItem(STORAGE_KEY, JSON.stringify(val))
  }
}